<script setup>
import { reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs';

import { getUserInfo, updateUser, setAvatar, getInviteUrl, destroyUser, updatePwd } from '../api/user.model'

const emit = defineEmits(['logout'])

const loading = ref(false)
const perfile = ref({})
const updatePwdmodel = ref(false)
const updatePwdFormRef = ref()
const updatePwdForm = reactive({})
const updatePwdRules = ref({
  oldPassword: [{ required: true, message: '请输入旧密码' }],
  password: [{ required: true, message: '请输入新密码' }],
  confirmPassword: [{ required: true, message: '请确认新密码' }, { validator: (rule, value) => {
      if (value !== updatePwdForm.password) {
        return Promise.reject(new Error('两次输入的新密码不一致!'))
      } else {
        return Promise.resolve()
      }
    }
  }]
})

const one = (str) => {
  return str && str.slice(0, 1)
}
const formatSex = (sex) => {
  if (!sex) return '未知'
  return {1: '男', 2: '女'}[sex]
}
const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

const updateProfile = () => {
  const { nickname, sex, signature } = perfile.value
  updateUser.send({ nickname, sex, signature }).then(() => {
    message.success('保存成功！')
  }).catch(() => {
    message.error('保存失败，请稍后再试！')
  })
}

const updateAvatar = (data) => {
  const { file } = data

  setAvatar.send({file: file}).then((url) => {
    perfile.value.avatar = url
  }).catch(() => {
    message.error('上传失败，请稍后再试！')
  })
}

const beforeUpload = (file) => {
  const isLt200k = file.size / 1024 <= 200
  if (!isLt200k) {
    message.error('图片大小不能超过200kb！')
  }
  return isLt200k
}

const onCopy = () => {
  message.success('您已成功复制邀请推广链接！')
}
const applyInviteCode = () => {
  getInviteUrl.send({
    registerUrl: window.location.origin + window.location.pathname,
    type: 'h5'
  }).then((code) => {
    perfile.value.invite_url = code
  })
}

const applyDestroyUser = () => {
  destroyUser.send().then(() => {
    message.success('注销成功！')
    setTimeout(() => {
      emit('logout')
    }, 2000)
  }).catch(() => {
    message.error('注销失败，请稍后再试！')
  })
}

const updatePassword = () => {
  updatePwdFormRef.value.validate().then(() => {
    const { oldPassword, password } = updatePwdForm
    updatePwd.send({ oldPassword, password }).then((res) => {
      if (res) {
        message.success('密码修改成功！')
        updatePwdmodel.value = false
        updatePwdForm.oldPassword = ''
        updatePwdForm.password = ''
        updatePwdForm.confirmPassword = ''
      }
    }).catch(() => {
      message.error('密码修改失败，请稍后再试！')
    })
  })
}

const getData = () => {
  loading.value = true
  getUserInfo.send().then((res) => {
    loading.value = false
    if (res) {
      perfile.value = res
      if (res.invite_code) applyInviteCode()
    }
  }).catch(() => {
    loading.value = false
  })
}
getData()
</script>
<template>
  <a-spin :spinning="loading">
    <div class="perfile">
      <div class="title">
        <h1>个人资料</h1>
      </div>

      <div class="perfile-content">
        <!-- 左边 -->
        <div class="perfile-left">
          <div class="perfile-form">
            <p><span class="label">性别：</span><a-radio-group v-model:value="perfile.sex" :options="[{label: '男', value: 1}, {label: '女', value: 2}, {label: '未知', value: 0}]"></a-radio-group></p>
            <p><span class="label">昵称：</span><a-input v-model:value="perfile.nickname" show-count :maxlength="20" style="width: 200px;"></a-input></p>
            <p><span class="label">个性签名：</span><a-textarea v-model:value="perfile.signature" show-count :maxlength="100" class="perfile-signature"></a-textarea></p>
            <!-- <p><span class="label">邀请码：</span><a href="javascript:;" class="invite-code">申请邀请推广</a></p> -->

            <p><span class="label"></span><a-button type="primary" @click="updateProfile">保存</a-button></p>
          </div>
          <div class="perfile-item">
            <h1>账号设置</h1>
            <ul class="account-ul">
              <li><span class="label">手机号：</span><span class="value">{{ perfile.phone || '未设置' }}</span><a href="javascript:;">修改</a></li>
              <li><span class="label">邮箱：</span><span class="value">{{ perfile.email || '未设置' }}</span><a href="javascript:;">修改</a></li>
              <li><span class="label">密码：</span><span class="value"></span><a href="javascript:;" @click="updatePwdmodel=true">修改</a></li>
              <li><span class="label">邀请推广：</span><span class="value">{{ perfile.invite_url || '未开通' }}</span>
                <a v-if="perfile.invite_code" href="javascript:;" v-clipboard:copy="perfile.invite_url" v-clipboard:success="onCopy">复制链接</a>
                <a-popconfirm
                  v-else
                  title="确定申请邀请推广吗？"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="applyInviteCode"
                >
                  <a href="javascript:;">申请</a>
                </a-popconfirm>
              </li>
              <li><span class="label">账号注销：</span><span class="value"></span>
                <a-popconfirm
                  title="确定注销账号吗？"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="applyDestroyUser"
                >
                  <a href="javascript:;">注销</a>
                </a-popconfirm>
              </li>
            </ul>
          </div>
        </div>
        <!-- 右边 -->
        <div class="perfile-mini">
          <div class="perfile-avatar">
            <div class="avatar-wrap">
              <a-avatar :src="perfile.avatar" :size="78">{{ one(perfile.nickname) }}</a-avatar>
              <a-upload accept="image/*" class="avatar-upload flex flex-center" :capture="null" :custom-request="updateAvatar" :show-upload-list="false" :before-upload="beforeUpload">
                <c-icon icon="PlusCircleOutlined" class="upload-icon"></c-icon>
                <span class="ai">点击修改头像</span>
              </a-upload>
            </div>

            <p>上传头像</p>
            <span class="avatar-tip">格式：支持JPG、PNG、JPEG，大小：200k以内</span>
          </div>
          <div class="perfile-info">
            <h1>基本信息</h1>
            <p>登录账号：<span>{{ perfile.username || '未设置' }}</span></p>
            <p>积分：<span>{{ formatSex(perfile.sex) }}</span></p>
            <p>注册时间：<span>{{ formatDate(perfile.createdAt) }}</span></p>
            <p>最后登录IP：<span>{{ perfile.last_ip }}</span></p>
            <p v-if="perfile.last_province">最后登录地：<span>{{ perfile.last_province }}{{ perfile.last_city }}</span></p>
            <p>最后登录时间：<span>{{ formatDate(perfile.last_lt) }}</span></p>
          </div>
        </div>
        <!-- 右边 end -->
      </div>

      <!-- 修改密码 -->
      <a-modal
        v-model:visible="updatePwdmodel"
        title="修改密码"
        :width="400"
        centered
        destroy-on-close
        :closable="false"
        :mask-closable="false">
        <a-form :model="updatePwdForm" :rules="updatePwdRules" ref="updatePwdFormRef" style="padding: 15px 0 0 20px">
          <a-form-item label="旧密码" name="oldPassword">
             <a-input type="password" v-model:value="updatePwdForm.oldPassword" show-count :maxlength="20" style="width: 200px;"></a-input>
          </a-form-item>
          <a-form-item label="新密码" name="password">
             <a-input type="password" v-model:value="updatePwdForm.password" show-count :maxlength="20" style="width: 200px;"></a-input>
          </a-form-item>
          <a-form-item label="确认密码" name="confirmPassword">
             <a-input type="password" v-model:value="updatePwdForm.confirmPassword" show-count :maxlength="20" style="width: 200px;"></a-input>
          </a-form-item>
        </a-form>
        <template #footer>
          <a-button type="primary" size="small" :loading="loading" @click="updatePassword">确认修改</a-button>
          <a-button size="small" @click.stop="updatePwdmodel=false">取消</a-button>
        </template>
      </a-modal>
    </div>
  </a-spin>
</template>
<style lang="less">
.perfile {
  .title {
    padding: 10px 0 6px;
    border-bottom: 1px solid #eee;
    h1 {
      font-size: 18px;
      font-weight: bold;
    }

  }

  .perfile-content {
    display: flex;
    justify-content: space-between;
    margin-top: 20px;
    h1 {
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }
    .perfile-mini {
      width: 300px;
      margin-left: 60px;
      .perfile-avatar {
        text-align: center;
        .avatar-wrap {
          width: 78px;
          height: 78px;
          display: inline-block;
          position: relative;
          .avatar-upload {
            position: absolute;
            z-index: 1;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            border-radius: 50%;
            opacity: 0;
            cursor: pointer;
            background-color: rgba(0, 0, 0, 0.68);

            .ai, .upload-icon {
              color: #fff;
              font-size: 12px;
              display: inline-block;
            }
            .upload-icon {
              font-size: 18px;
            }
          }
          &:hover .avatar-upload {
            opacity: 1;
          }
        }
        .avatar-tip {
          color: #999;
          font-size: 12px;
          margin-top: 5px;
        }
        p {
          margin: 8px 0;
        }
      }
      .perfile-info {
        margin-top: 20px;
        h1 {
          font-size: 16px;
          color: #333;
          margin-bottom: 20px;
        }
        p {
          font-size: 14px;
          color: #444;
          span {
            color: #666;
            font-size: 12px;
          }
        }
      }
    }
    .perfile-left {
      flex: 1;
      .perfile-form {
        padding: 20px 0;
        p {
          padding: 0 0 20px;
          margin: 0;
          &:last-child {
            padding-bottom: 0;
          }
          span.label {
            display: inline-block;
            width: 80px;
            font-size: 14px;
            color: #333;
          }
        }
        .invite-code {
          color: #1890ff;
        }
      }
      .account-ul {
        width: 100%;
        padding-top: 10px;
        li {
          padding: 15px 12px 15px 0;
          border-bottom: 1px solid #eee;
          span {
            display: inline-block;
            width: 80px;
            font-size: 14px;
            color: #333;
          }
          .value {
            font-size: 14px;
            color: #666;
            margin-left: 10px;
          }
        }
        a {
          float: right;
          margin-left: 10px;
          font-size: 14px;
          color: #1890ff;
          text-decoration: none;
        }
      }


    }
    .perfile-signature {
      width: 580px;
      display: inline-block;
    }
  }
}
@media screen and (max-width: 735px) {
  .perfile {
    .perfile-content {
      flex-direction: column-reverse;
      margin-top: 0;
      .perfile-mini {
        width: 100%;
        margin-left: 0;
        margin-top: 20px;
      }
      .perfile-signature {
        width: 260px;
      }
    }

  }
}
</style>
